﻿using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace Coder.Workflow.Stores.Ef
{
    public class WorkProcessStore<T> : IWorkProcessStore<T> where T : WorkflowDbContext
    {
        private readonly T _context;

        public WorkProcessStore(T context)
        {
            _context = context;
        }

        public WorkProcess GetById(int id)
        {
            return _context.Set<WorkProcess>().Include(f => f.Items).FirstOrDefault(f => f.Id == id);
            //return _context.DelegateOrderWorkflows.Include(f => f.Items).FirstOrDefault(f => f.Id == id);
        }

        public TWorkProcess Get<TWorkProcess>(string name = null) where TWorkProcess : WorkProcess
        {
            return _context.Set<TWorkProcess>().Include(f => f.Items)
                .ThenInclude(f => f.Role)
                .FirstOrDefault(_ => name == null || name == _.Name);
        }

        public WorkProcess GetByName(string name)
        {
            var wf = _context.Set<WorkProcess>().Include(f => f.Items).ThenInclude(f => f.Role)
                .FirstOrDefault(f => f.Name == name);

            _context.Entry(wf).State = EntityState.Detached;
            return wf;
        }
    }
}